﻿using System;
using System.Net.Mail;
using System.Text;
using System.Web.Mvc;
using GBFinance.Web.Models;
using HiLand.Framework.BusinessCore;
using HiLand.Framework.BusinessCore.BLL;
using HiLand.Framework4.Permission.Attributes;
using HiLand.Utility.Data;
using HiLand.Utility.Entity;
using HiLand.Utility.Enums;
using HiLand.Utility.IO;
using HiLand.Utility.Setting;
using HiLand.Utility.Web;
using HiLand.Utility4.MVC.Data;

namespace GBFinance.Web.Areas.Broker.Controllers
{
    public class AccountController : Controller
    {
        /// <summary>
        /// 修改口令
        /// </summary>
        /// <returns></returns>
        public ActionResult ChangePassword()
        {
            return View();
        }

        /// <summary>
        /// 显示和修改代理商信息
        /// </summary>
        /// <returns></returns>
        [UserAuthorize(UserTypes.Broker)]
        public ActionResult BrokerInformation()
        {
            Guid currentUserGuid = BusinessUserBLL.CurrentUser.UserGuid;
            BrokerEntity brokerEntity = Converter.InheritedEntityConvert<BusinessUser, BrokerEntity>(BusinessUserBLL.Get(currentUserGuid));
            return View(brokerEntity);
        }

        public ActionResult Register()
        {
            return View();
        }

        public ActionResult _BrokerInformation(string brokerGuid="",bool isDisplaySubmitButton= false)
        {
            BrokerEntity brokerEntity = BrokerEntity.Empty;
            if (string.IsNullOrWhiteSpace(brokerGuid) == false && brokerGuid != Guid.Empty.ToString())
            {
                brokerEntity = Converter.InheritedEntityConvert<BusinessUser, BrokerEntity>(BusinessUserBLL.Get(new Guid(brokerGuid)));
            }

            this.PassParam<bool>("isDisplaySubmitButton", isDisplaySubmitButton);
            return View(brokerEntity);
        }

        [HttpPost]
        public ActionResult _BrokerInformation(BrokerEntity model)
        {
            LogicStatusInfo logicStatusInfo = new LogicStatusInfo();
            CreateUserRoleStatuses createStatus = CreateUserRoleStatuses.Successful;

            if (model.UserGuid == Guid.Empty)
            {
                //设置其他缺省属性
                model.UserRegisterDate = DateTime.Now;
                model.UserStatus = UserStatuses.Unactivated;
                model.UserType = UserTypes.Broker;

                BusinessUserBLL.CreateUser(model, out createStatus);

                if (createStatus == CreateUserRoleStatuses.Successful)
                {
                    //1.发送激活邮件
                    try
                    {
                        using (SmtpClient smtpClient = new SmtpClient())
                        {
                            MailMessage mailMessage = GetMail(model);
                            smtpClient.Send(mailMessage);
                        }


                        //2.跳转到注册成功提示页面
                        //return RedirectToAction("RegisterSuccess");
                        logicStatusInfo.IsSuccessful = true;
                    }
                    catch (Exception ex)
                    {
                        logicStatusInfo.IsSuccessful = false;
                        logicStatusInfo.Message = ex.Message;
                    }
                }
                else
                {
                    string errorInformation = string.Empty;
                    switch (createStatus)
                    {
                        case CreateUserRoleStatuses.FailureDuplicateEMail:
                            errorInformation = "Sorry,Duplicate EMail.";
                            break;
                        case CreateUserRoleStatuses.FailureDuplicateName:
                            errorInformation = "Sorry，Duplicate Name";
                            break;
                        case CreateUserRoleStatuses.FailureUnknowReason:
                            errorInformation = "Sorry，Unknow Reason Failure";
                            break;
                        default:
                            break;
                    }
                    logicStatusInfo.IsSuccessful = false;
                    logicStatusInfo.Message = errorInformation;
                }
            }
            else
            {
                BrokerEntity brokerEntityOriginal = Converter.InheritedEntityConvert<BusinessUser, BrokerEntity>(BusinessUserBLL.Get(model.UserGuid));
                model.UserType = brokerEntityOriginal.UserType;
                model.UserRegisterDate = brokerEntityOriginal.UserRegisterDate;
                model.UserStatus = brokerEntityOriginal.UserStatus;
                model.Password = brokerEntityOriginal.Password;

                logicStatusInfo.IsSuccessful = BusinessUserBLL.UpdateUser(model);
            }

            return Json(logicStatusInfo);
        }

        /// <summary>
        /// 注册成功的提示页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterSuccess()
        {
            return View();
        }

        /// <summary>
        /// 邮件激活
        /// </summary>
        /// <returns></returns>
        public ActionResult RegisterActive()
        {
            string brokerGuid = RequestHelper.GetValue("bk");
            LogicStatusInfo DataObject = new LogicStatusInfo();
            if (string.IsNullOrWhiteSpace(brokerGuid))
            {
                DataObject.IsSuccessful = false;
                DataObject.Message = "No broker information is mentioned";
            }
            else
            {
                BusinessUser brokerEntity = BusinessUserBLL.Get(new Guid(brokerGuid));
                if (brokerEntity.IsEmpty == true)
                {
                    DataObject.IsSuccessful = false;
                    DataObject.Message = "No broker information is mentioned";
                }
                else
                {
                    if (brokerEntity.UserStatus == UserStatuses.Unactivated)
                    {
                        bool isSuccessful = BusinessUserBLL.SetUserStatus(brokerEntity.UserGuid, UserStatuses.Normal);

                        if (isSuccessful == true)
                        {
                            DataObject.IsSuccessful = true;
                            DataObject.Message = string.Format("This broker has beed actived.Please <a href='{0}'>login</a>", Url.Action("Index", "Main"));
                        }
                        else
                        {
                            DataObject.IsSuccessful = false;
                            DataObject.Message = "No broker information is mentioned";
                        }
                    }
                    else
                    {
                        DataObject.IsSuccessful = false;
                        DataObject.Message = "This broker cannot be active(because it has beed actived or other reason).";
                    }
                }
            }


            return View(DataObject);
        }
        #region 辅助方法
        /// <summary>
        /// 构建发送的邮件信息
        /// </summary>
        /// <param name="brokerEntity"></param>
        /// <returns></returns>
        [NonAction]
        private MailMessage GetMail(BusinessUser brokerEntity)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.IsBodyHtml = true;
            MailAddress fromAddress = new MailAddress("cashsolution.com.au@gmail.com", "Golden Bridge Finance");
            MailAddress toAddress = new MailAddress(brokerEntity.UserEmail, brokerEntity.UserNameJointing);

            mailMessage.From = fromAddress;
            mailMessage.To.Add(toAddress);
            mailMessage.Subject = "You have successfully registered your interest as a broker with Golden Bridge Finance";


            string brokerActiveUrl = Url.Action("RegisterActive", "Account", new { bk = brokerEntity.UserGuid });
            string siteUrl = Config.GetAppSetting("siteUrl", "http://www.goldenbridgefinance.com.au/");
            brokerActiveUrl = PathHelper.CombineForVirtual(siteUrl, brokerActiveUrl);

            StringBuilder messageBody = new StringBuilder();
            messageBody.AppendLine("Dear Sir/Madam,<br/>");
            messageBody.AppendFormat("You have successfully registered your interest as a broker with Golden Bridge Finance. To verify your account, please click the following link: <a href='{0}'>Active</a>,If you're unable to click the link above, copy and paste it into your web browser:  {0}<br/>",
                brokerActiveUrl);
            messageBody.Append("Please do not reply to this email. If you have any queries please email to info@goldenbridgefinance.com.au<br/>");
            messageBody.Append("<br/><br/>");
            messageBody.Append("Kind Regards,");
            messageBody.Append("<br/>");
            messageBody.Append("The team of Golden Bridge Finance");

            mailMessage.Body = messageBody.ToString();

            return mailMessage;
        }
        #endregion
    }
}
